package cn.edu.zafu.bigdata.YinMingyan.chapter11;

import java.io.*;
import java.net.*;

// 简单的TCP聊天客户端
public class TCPChatClient {
    public static void main(String[] args) {
        String serverAddress = "192.168.16.16"; // 本机服务器地址
        int port = 5678; //本机端口号
        //String serverAddress = "192.168.16.15"; // 连接的同学的服务器,同学的局域网IP地址
        //int port = 9999; // 同学服务器端口号

        try (Socket socket = new Socket(serverAddress, port)) {
            System.out.println("TCP Connected to server at " + serverAddress + ":" + port);

            // 获取输入输出流
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            // 读取服务器回复的消息
            new Thread(() -> {
                try {
                    String serverResponse;
                    while ((serverResponse = in.readLine()) != null) {
                        System.out.println("TCP Server says: " + serverResponse);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 发送消息到服务器
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
            }
        } catch (UnknownHostException e) {
            System.err.println("Server not found: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("I/O Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}